package com.lfg.learn.other;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class MaxNums {

    public static void main(String[] args) {
        System.out.println(maxNums(2236222, new int[]{2, 3, 7}));
    }

    public static int maxNums(int target, int[] nums) {
        Arrays.sort(nums);
        Set<Integer> set = new HashSet<>(nums.length);
        int max = 0;
        for (int num : nums) {
            set.add(num);
            max = Math.max(max, num);
        }
        String d = String.valueOf(target);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < d.length(); i++) {
            int n = d.charAt(i) - '0';
            if (!set.contains(n) || i == d.length() - 1) {
                Integer l = null;
                while (true) {
//                    if (!set.contains(n)) {
                        l = lessNum(nums, n);
//                    }

                    if (l == null) {
                        if(i == 0){
                            sb.delete(0, sb.length());
                            for (int j = 0; j < d.length()-1; j++) {
                                sb.append(nums[nums.length-1]);
                            }
                            return Integer.parseInt(sb.toString());
                        }
                        i--;
                        n = sb.charAt(sb.length() - 1) - '0';
                        sb.deleteCharAt(sb.length() - 1);
                        continue;
                    }
                    break;
                }
                sb.append(l);
                while (i < d.length()) {
                    sb.append(max);
                    i++;
                }
            } else {
                sb.append(n);
            }
        }
        return Integer.parseInt(sb.toString());
    }

    private static Integer lessNum(int[] nums, int n) {
        for (int j = 0; j < nums.length; j++) {
            if (nums[j] >= n) {
                if (j == 0) {
                    return null;
                }
                j--;
                return nums[j];
            }
        }
        return null;
    }
}
